/*
 * Copyright (C) 2010-2012 Susanta Tewari
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package commons.util;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Susanta Tewari
 * @version 1.2.3
 * @history Created on Sep 27, 2012.
 * @since 1.2.3
 */
public final class ListUtil {

    /**
     * Constructs ...
     *
     */
    private ListUtil() {}

    /**
     * @param <T> list element type
     * @param list1 list 1
     * @param list2 list 2
     * @return total number of mismatches
     */
    public static <T> int countDiff(List<T> list1, List<T> list2) {


        // null
        if (list1 == null) {
            ExceptionUtil.throwIllegalArgExNull("list1");
        }

        if (list2 == null) {
            ExceptionUtil.throwIllegalArgExNull("list2");
        }


        // empty
        if (list1.isEmpty()) {

            ExceptionUtil.throwIllegalArgEx(ArrayUtil.class, "ArrayUtil_Collection_Is_Empty",
                                            "list1");
        }

        if (list2.isEmpty()) {

            ExceptionUtil.throwIllegalArgEx(ArrayUtil.class, "ArrayUtil_Collection_Is_Empty",
                                            "list2");
        }


        // length mismatch
        if (list2.isEmpty()) {
            ExceptionUtil.throwIllegalArgEx(ArrayUtil.class, "Length_Mismtach");
        }

        int result = 0;

        for (int i = 0; i < list1.size(); i++) {

            if (!list1.get(i).equals(list2.get(i))) {
                result++;
            }
        }

        return result;
    }

    /**
     * Source: http://stackoverflow.com/a/12864584/225866
     * @param items
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> toList(Object... items) {

        List<T> list = new ArrayList<T>();

        if ((items.length == 1) && items[0].getClass().isArray()) {

            int length = Array.getLength(items[0]);

            for (int i = 0; i < length; i++) {

                Object element = Array.get(items[0], i);
                T item         = (T) element;

                list.add(item);
            }

        } else {

            for (Object i : items) {

                T item = (T) i;

                list.add(item);
            }
        }

        return list;
    }
}
